package com.lvshi0797.cms.service;

import java.security.NoSuchAlgorithmException;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lvshi0797.cms.dao.IManagerDao;
import com.lvshi0797.cms.entities.FManager;
import com.lvshi0797.cms.helper.BussinessException;
import com.lvshi0797.cms.helper.CommonUtils;
import com.lvshi0797.cms.helper.SecurityUtil;
@Service("managerService")
public class ManagerService implements IManagerService {
	@Autowired
	private IManagerDao managerDao;

	@Override
	public FManager login(String username, String password)
			throws BussinessException {
		FManager manager = null;
		if(username==null||password==null){
			throw new BussinessException("用户名和密码都不能为空！");
		}
		if(!CommonUtils.isMobileNO(username)){//手机号码登录
			manager = managerDao.findByusername(username);
		}else{
			manager = managerDao.findByphone(username);
		}
		if(manager==null){
			throw new BussinessException("用户名不存在！");
		}
		String pwd = "";
		try {
			pwd = SecurityUtil.md5(manager.getUsername(), password);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		if(!pwd.equals(manager.getPassword())){
			throw new BussinessException("用户名或密码不正确！");
		}
		return manager;
	}
	/**
	 * 添加管理员
	 * 	1.填手机的不能重复 这个在客户端以及数据库都有判断
	 *  2.用户名username不能为空，并且不能重复 这个在客户端以及数据库都有判断
	 *  3.添加addTime时间
	 *  4.deptName不能为空
	 *  5.town所辖乡镇不能为空
	 * @param manager
	 * @throws BussinessException
	 */
	@Override
	public void addManager(FManager manager) throws BussinessException {
		if(manager==null||manager.getUsername()==null||manager.getPassword()==null||manager.getTown()==null||manager.getDeptName()==null){
			throw new BussinessException("您提交的信息不全，请重新提交！");
		}
		manager.setAddTime(new Date());
		try {
			manager.setPassword(SecurityUtil.md5(manager.getUsername(), manager.getPassword()));
		} catch (NoSuchAlgorithmException e) {
			throw new BussinessException("密码加密出错！"+e.getMessage());
		}
		managerDao.add(manager);
	}

	@Override
	public boolean checkTelAvailable(String phone) {
		return managerDao.checkTelAvailable(phone);
	}

	@Override
	public boolean checkUsernameAvailable(String username) {
		return managerDao.checkUsernameAvailable(username);
	}
	@Override
	public void updateManager(FManager manager) throws BussinessException{
		if(manager==null||manager.getId()<=0){
			throw new BussinessException("当前操作失败，请稍后重试！");
		}
		FManager manager2 = managerDao.load(manager.getId());
		manager.setAddTime(manager2.getAddTime());
		manager.setTown(manager2.getTown());
		manager.setUsername(manager2.getUsername());
		managerDao.update(manager);
		
	}
	@Override
	public FManager loadFManager(int id) throws BussinessException{
		FManager manager = managerDao.load(id);
		if(manager==null){
			throw new BussinessException("该用户不存在！");
		}
		return manager;
	}

	 

}
